package com.sscn.tts

import android.content.Context
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
class SystemTtsEngine(context: Context, onInit: () -> Unit): UtteranceProgressListener() {
    // 系统TTS引擎
    private val tts = TextToSpeech(context) {
        onInit()
    }.apply {
        setOnUtteranceProgressListener(this@SystemTtsEngine)
    }
    private var onStartListener: ((String?) -> Unit)? = null
    private var onStopListener: ((String?, Boolean) -> Unit)? = null
    private var onDoneListener: ((String?) -> Unit)? = null
    private var onErrorListener: ((String?, Int) -> Unit)? = null
    fun speak(text: String, utteranceId: String = "") {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId, )
    }
    fun stop() {
        tts.stop()
    }
    fun setOnStartListener(onStart: ((String?) -> Unit)?) {
        onStartListener = onStart
    }
    fun setOnStopListener(onStop: ((String?, Boolean) -> Unit)?) {
        onStopListener = onStop
    }
    fun setOnErrorListener(onError: ((String?, Int) -> Unit)?) {
        onErrorListener = onError
    }
    fun setOnDoneListener(onDone: ((String?) -> Unit)?) {
        onDoneListener = onDone
    }
    fun release() {
        tts.shutdown()
    }
    override fun onStart(utteranceId: String?) {
        onStartListener?.let { it(utteranceId) }
    }
    override fun onDone(utteranceId: String?) {
        onDoneListener?.let { it(utteranceId) }
    }

    override fun onStop(utteranceId: String?, interrupted: Boolean) {
        super.onStop(utteranceId, interrupted)
    }
    @Suppress
    override fun onError(utteranceId: String?) {}
    override fun onError(utteranceId: String?, errorCode: Int) {
        super.onError(utteranceId, errorCode)
        onErrorListener?.let { it(utteranceId, errorCode) }
    }
}